import axios from "axios";

const instance = axios.create({
    baseURL: 'http://localhost:8080',
    headers: {
        Authorization: 'Bearer ' + localStorage.getItem("token")
    }
});

/// axios 发布与订阅处理类
class HttpEventEmitter {

    handlers = {
        "PARAM_CHECK_FAILED": new Set(),
        "INVALID_TOKEN": new Set(),
        "LOGIN_SUCCESS": new Set(),
    }

    constructor() {
        // 请求拦截器
        instance.interceptors.request.use(
            this.reqSuccessHandler,
            this.reqErrorHandler
        )

        // 响应拦截器
        instance.interceptors.response.use(
            this.respSuccessHandler,
            this.respErrorHandler
        )
        this.http = instance;
    }

    // 请求成功拦截处理函数
    reqSuccessHandler = (config) => {
        config.headers.Authorization = 'Bearer ' + localStorage.getItem("token");
        return config;
    }

    reqErrorHandler = (error) => {
        return error;
    }

    // 拦截响应成功处理方法
    respSuccessHandler = (resp) => {
        console.log(">>>>>>>>>", resp.data);
        // 登录成功后返回token，
        if (resp.data.token) {
            this.emit('LOGIN_SUCCESS');
        }
        return resp.data;
    }

    // 拦截响应失败处理方法
    respErrorHandler = (error) => {
        const code = error.response.status;
        switch (code) {
            case 400:
                this.emit('PARAM_CHECK_FAILED');
                break;
            case 401:
                this.emit('INVALID_TOKEN')
                break;
            default:
                break;
        }
    }

    // 注册事件
    listen = (eventName, handler) => {
        this.handlers[eventName].add(handler);
    }

    // 触发处理函数
    emit = (eventName, ...args) => {
        this.handlers[eventName].forEach(handler => handler(...args))
    }

}


export default new HttpEventEmitter();